package com.aletto.general_store.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.entities.WalletAccount;
import com.aletto.general_store.data.model.Response;
import com.aletto.general_store.data.model.Upload;
import com.aletto.general_store.data.model.UserDetails;
import com.aletto.general_store.presenters.core.SimpleParamsTemplate;
import com.aletto.general_store.presenters.core.SimpleTemplate;
import com.aletto.general_store.ui.popup.DeleteWalletPopup;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.WalletAccountLocalStore;
import com.aletto.general_store.utils.XHelper;
import com.aletto.general_store.utils.event.FinishEvent;
import com.aletto.general_store.utils.image.GlideApp;
import com.aletto.general_store.utils.image.GlideEngine;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;
import com.sisyphus.spinach.network.views.ToastView;

import java.io.File;
import java.util.ArrayList;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * 编辑用户信息，或者钱包
 */
public class ProfileActivity extends AppCompatActivity {

    public static Intent newIntent(Context context, String address) {
        Intent intent = new Intent(context, ProfileActivity.class);
        intent.putExtra("ADDRESS", address);
        return intent;
    }

    private UserDetails mUserDetails;
    private String      address;
    private View        ivDelete;
    private ImageView   ivAvatar;
    private TextView    tv_wallet_name, tv_signature, walletAddress;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        XHelper.initTitle(this, R.string.title_profile);

        // 关闭此前页面
        EventBus.getDefault().post(new FinishEvent(WalletImportActivity.class));

        ivAvatar = findViewById(R.id.iv_avatar);
        tv_wallet_name = findViewById(R.id.tv_wallet_name);
        tv_signature = findViewById(R.id.tv_signature);
        walletAddress = findViewById(R.id.tv_wallet_address);
        ivDelete = findViewById(R.id.iv_delete);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Intent intent = getIntent();
        if (intent != null) {
            address = intent.getStringExtra("ADDRESS");
            walletAddress.setText(address);
            userDetailsTemplate.setParams(address).execute(getLifecycle());

            // 删除账户
            ivDelete.setOnClickListener(v ->
                    new XPopup.Builder(this)
                            .asCustom(new DeleteWalletPopup(v.getContext(), address)).show());
        }
    }

    private void pictureSelector(ImageView ivAvatar) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .isDisplayCamera(false)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setCompressEngine(new CompressFileEngine() {
                    @Override
                    public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
                        Luban.with(context).load(source).ignoreBy(100)
                                .setCompressListener(new OnNewCompressListener() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onSuccess(String source, File compressFile) {
                                        if (call != null) {
                                            call.onCallback(source, compressFile.getAbsolutePath());
                                        }
                                    }

                                    @Override
                                    public void onError(String source, Throwable e) {
                                        if (call != null) {
                                            call.onCallback(source, null);
                                        }
                                    }
                                }).launch();
                    }

                })
                .forResult(new OnResultCallbackListener<>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        String realPath = result.get(0).getRealPath();
                        GlideApp.with(ivAvatar).load(realPath).avatar().into(ivAvatar);

                        upload(new File(realPath)).execute();
                    }

                    @Override
                    public void onCancel() {

                    }

                });
    }

    private SimpleTemplate<Object> upload(File file) {
        return new SimpleTemplate<>() {

            @Override
            public INetTask.View<Object> view() {

                return new ToastView<>(getApplicationContext());
            }

            @Override
            public INetTask.Presenter<Object, INetTask.View<Object>> presenter() {
                return new NetSingleTask<>(
                        DataRepository.getInstance().upload(file)
                                .flatMap((Function<Response<Upload>, ObservableSource<Response<Object>>>) response -> {
                                    Upload data = response.getData();
                                    WalletAccount wallet = LocalConfigStore.getInstance().getWallet();
                                    WalletAccountLocalStore.getInstance().updateAvatar(wallet.getAddress(), data.getUrl());
                                    return DataRepository.getInstance().updateUserDetails(mUserDetails.getId(), null, data.getUrl(), null);
                                })
                );
            }
        };
    }

    private final SimpleParamsTemplate<UserDetails, String> userDetailsTemplate = new SimpleParamsTemplate<>() {
        @Override
        public INetTask.View<UserDetails> view() {
            return new INetTask.View<>() {
                @Override
                public void success(UserDetails data) {

                    // 头像
                    findViewById(R.id.layout_avatar).setOnClickListener(v -> pictureSelector(ivAvatar));

                    findViewById(R.id.layout_nickname).setOnClickListener(v -> // 昵称
                            startActivity(UserNicknameActivity.newIntent(v.getContext(), data.getId(), address)));

                    findViewById(R.id.layout_sign).setOnClickListener(v -> // 签名
                            startActivity(UserSignActivity.newIntent(v.getContext(), data.getId())));

                    tv_wallet_name.setText(data.getName());
                    tv_signature.setText(data.getSign());

                    if (mUserDetails == null) {
                        GlideApp.with(ivAvatar.getContext()).load(data.getHead_img()).avatar().into(ivAvatar);
                    }

                    mUserDetails = data;
                }
            };
        }

        @Override
        public INetTask.Presenter<UserDetails, INetTask.View<UserDetails>> presenter() {
            return new NetSingleTask<>(DataRepository.getInstance().login(params[0]));
        }
    };

}
